package com.pinyoumei.app.activity.wallet;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.pinyoumei.app.R;
import com.pinyoumei.app.activity.BaseActivityCurrency;
import com.pinyoumei.app.bean.BaseBean;
import com.pinyoumei.app.network.Constants;
import com.pinyoumei.app.utils.EventBusUtils;
import com.pinyoumei.app.utils.SPUtils;
import com.pinyoumei.app.utils.SignatureUtils;
import com.pinyoumei.app.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AddBankCardActivity extends BaseActivityCurrency implements View.OnClickListener {

    private ImageView abcvBack;
    private EditText abcvCardName,abcvCardNum;
    private TextView abcvBackName,abcvSub;

    @Override
    protected int layoutId() {
        return R.layout.add_back_card_view;
    }

    @Override
    protected void initView() {
        abcvBack = findViewById(R.id.abcv_back);
        abcvCardName = findViewById(R.id.abcv_card_name);
        abcvCardNum = findViewById(R.id.abcv_card_num);
        abcvBackName = findViewById(R.id.abcv_back_name);
        abcvSub = findViewById(R.id.abcv_sub);
        abcvBack.setOnClickListener(this);
        abcvSub.setOnClickListener(this);
        abcvCardNum.addTextChangedListener(textWatcher);
    }

    @Override
    protected void initData() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.abcv_back:
                finish();
                break;
            case R.id.abcv_sub:
                if(TextUtils.isEmpty(abcvBackName.getText().toString()) || TextUtils.equals(abcvBackName.getText().toString(),"不支持该银行")){
                    ToastUtils.showLong("不支持该银行,请更换银行卡");
                    return;
                }
                bankInfoSave(SPUtils.getAppUserId(this));
                break;
        }
    }

    TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if(checkBankCard(s.toString())){
                BankCardUtil bankinfobean = new BankCardUtil(s.toString());
                String bnStr = SPUtils.getBankName(bankinfobean.getBankName());
                abcvBackName.setText(TextUtils.isEmpty(bnStr)?"不支持该银行":SPUtils.getBankName(bankinfobean.getBankName()));
            }else{
                abcvBackName.setText("");
            }
        }
    };


    /**校验过程：
     1、从卡号最后一位数字开始，逆向将奇数位(1、3、5等等)相加。
     2、从卡号最后一位数字开始，逆向将偶数位数字，先乘以2（如果乘积为两位数，将个位十位数字相加，即将其减去9），再求和。
     3、将奇数位总和加上偶数位总和，结果应该可以被10整除。
     * 校验银行卡卡号
     */
    public static boolean checkBankCard(String bankCard) {
        if(bankCard.length() < 15 || bankCard.length() > 19) {
            return false;
        }
        char bit = getBankCardCheckCode(bankCard.substring(0, bankCard.length() - 1));
        if(bit == 'N'){
            return false;
        }
        return bankCard.charAt(bankCard.length() - 1) == bit;
    }

    /**
     * 从不含校验位的银行卡卡号采用 Luhn 校验算法获得校验位
     * @param nonCheckCodeBankCard
     * @return
     */
    public static char getBankCardCheckCode(String nonCheckCodeBankCard){
        if(nonCheckCodeBankCard == null || nonCheckCodeBankCard.trim().length() == 0
                || !nonCheckCodeBankCard.matches("\\d+")) {
            //如果传的不是数据返回N
            return 'N';
        }
        char[] chs = nonCheckCodeBankCard.trim().toCharArray();
        int luhmSum = 0;
        for(int i = chs.length - 1, j = 0; i >= 0; i--, j++) {
            int k = chs[i] - '0';
            if(j % 2 == 0) {
                k *= 2;
                k = k / 10 + k % 10;
            }
            luhmSum += k;
        }
        return (luhmSum % 10 == 0) ? '0' : (char)((10 - luhmSum % 10) + '0');
    }

    private void bankInfoSave(String userId){
        String bankAcNo = abcvCardNum.getText().toString();
        String bankAcName = abcvCardName.getText().toString();
        String bname = abcvBackName.getText().toString();
        if(!bname.equals("不支持该银行")) {
            String bankCode = SPUtils.getBankCord(bname);
            String bankName = SPUtils.getBankName(bname);
            Map<String, Object> map = new HashMap<>();
            map.put("id", "");
            map.put("userId", userId);
            map.put("bankAcNo", bankAcNo);
            map.put("bankAcName", bankAcName);
            map.put("bankCode", bankCode);
            map.put("bankName", bankName);
            OkGo.<String>post(Constants.bankInfoSave)
                    .params("id", "")
                    .params("userId", userId)
                    .params("bankAcNo", bankAcNo)
                    .params("bankAcName", bankAcName)
                    .params("bankCode", bankCode)
                    .params("bankName", bankName)
                    .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                    .execute(new StringCallback() {

                        @Override
                        public void onStart(Request<String, ? extends Request> request) {
                            super.onStart(request);
                            loadingDailog.show();
                        }

                        @Override
                        public void onSuccess(Response<String> response) {
                            loadingDailog.dismiss();
                            BaseBean bean = gson.fromJson(response.body(), BaseBean.class);
                            if (bean.getCode() == 1){
                                selectBankInfo(SPUtils.getAppUserId(AddBankCardActivity.this));
                            }
                        }

                        @Override
                        public void onError(Response<String> response) {
                            super.onError(response);
                            loadingDailog.dismiss();
                        }
                    });


        }


    }

    private void selectBankInfo(String user_id){
        Map<String, Object> map = new HashMap<>();
        map.put("userId",user_id);
        OkGo.<String>post(Constants.bankInfolist)
                .params("userId", user_id)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {

                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        loadingDailog.dismiss();
                        BankCardListBean bean = gson.fromJson(response.body(), BankCardListBean.class);
                        EventBusUtils.post(bean.getResult());
                        finish();
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }
                });
    }





}
